package cn.player.act.vod;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import cn.player.R;
import cn.player.act.BaseActivity;
import cn.player.act.MediaPlayActivity;
import cn.player.entity.ColumnInfoItem;
import cntv.player.engine.Const;
import cn.player.media.entity.VideoInfo;
import cn.player.media.util.ParseUtil;

public class ColumnDetailActivity extends BaseActivity {

    private String mUrlColumnDetail;
    private String columnID;
    private int pagesize = 20;
    private int pagenum;
    private boolean isRefreshDone;
    private boolean isRefresh;
    private int total;

    private LinearLayout mLlLoading;
    private ListView mLvColumnDetail;
    private List<ColumnInfoItem> columnInfoItems;
    private DataAdapter dataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.column_detail_activity);

        findViews();
        setListensers();
        initializeDate();

    }


    private void initializeDate() {
        // TODO Auto-generated method stub
        columnID = getIntent().getStringExtra("columnID");
        mUrlColumnDetail = getColumnPath(++pagenum);

        columnInfoItems = new ArrayList<ColumnInfoItem>();
        initJsonData(mUrlColumnDetail);
    }


    private void setListensers() {
        // TODO Auto-generated method stub
        mLvColumnDetail.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // TODO Auto-generated method stub
                Intent mediaPlayIntent = new Intent(mContext, MediaPlayActivity.class);
                VideoInfo videoInfo = new VideoInfo();
                //点播基本信息
                videoInfo.setPort(true);
                videoInfo.setFlag(Const.VOD);
                videoInfo.setTitle(columnInfoItems.get(position).getVideoTitle());
                videoInfo.setVid(columnInfoItems.get(position).getVideoPlayID());

                mediaPlayIntent.putExtra(VideoInfo.class.getName(), videoInfo);
                startActivity(mediaPlayIntent);
                overridePendingTransition(R.anim.base_push_right_in, R.anim.base_fade_out);
            }
        });

        mLvColumnDetail.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub
                if (totalItemCount != 0 && (firstVisibleItem + visibleItemCount == totalItemCount)) {
                    if (!isRefreshDone && !isRefresh) {
                        if (columnInfoItems.size() < total) {
                            isRefresh = true;
                            refreshList();
                        } else {
                            loadMoreComplete();
                        }
                    }
                }
            }
        });
    }

    /**
     * 加载更多完成
     */
    private void loadMoreComplete() {
        isRefresh = false;
        isRefreshDone = true;
//		mLvVideoList.onLoadComplete();
//		ToastUtil.showToast(mContext, R.string.msg_loaded_complete, Toast.LENGTH_SHORT);
    }


    private void findViews() {
        // TODO Auto-generated method stub
        mLvColumnDetail = (ListView) findViewById(R.id.lv_column_detail);

        mLlLoading = (LinearLayout) findViewById(R.id.ll_loading);
        mLvColumnDetail.setEmptyView(mLlLoading);
    }


    private String getColumnPath(int pagenum) {
        String urlColumnDetail = "http://hot.news.cntv.cn/index.php?controller=lanmu"
                + "&action=getvideolist&sort=desc&id=" + columnID
                + "&n=" + pagesize + "&p=" + pagenum
                + "&st=20130101&et=" + getToday();

        return urlColumnDetail;
    }

    // 获取当前日期
    public String getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
        Date d = new Date();
        String date = sdf.format(d);
        return date;
    }


    @Override
    protected void initDataSuccess(String url, JSONObject response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        try {
            total = response.optInt("total");
            List<ColumnInfoItem> tempData = ParseUtil.parseDataToCollection(response, "videoList", ColumnInfoItem.class);

            columnInfoItems.addAll(tempData);
            if (dataAdapter == null) {
                dataAdapter = new DataAdapter(columnInfoItems);
                mLvColumnDetail.setAdapter(dataAdapter);
            } else {
                dataAdapter.setData(columnInfoItems);
                dataAdapter.notifyDataSetChanged();
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            isRefresh = false;
        }
    }

    private void refreshList() {
        mUrlColumnDetail = getColumnPath(++pagenum);
        initJsonData(mUrlColumnDetail);
    }


    private class DataAdapter extends BaseAdapter {

        private List<ColumnInfoItem> data;
        private ViewHolder viewHolder;

        public DataAdapter(List<ColumnInfoItem> data) {
            super();
            this.data = data;
        }

        public void setData(List<ColumnInfoItem> data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            // return data.size();
            return data.size();
        }

        @Override
        public Object getItem(int index) {
            // TODO Auto-generated method stub
            return data.get(index);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.columnlist_info_row, null);

                viewHolder = new ViewHolder();
                viewHolder.row_img = (ImageView) convertView.findViewById(R.id.row_img);
                viewHolder.row_title = (TextView) convertView.findViewById(R.id.row_title);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }


            finalBitmap.display(viewHolder.row_img, data.get(position).getVideoImage());
            viewHolder.row_title.setText(data.get(position).getVideoTitle());

            return convertView;
        }

        class ViewHolder {
            ImageView row_img;
            TextView row_title;
        }
    }

}
